var oldCustomerId = '',supplierId='',$quantityTotal=$('#quantityTotal'),$totalPriceTotal=$('#totalPrice'),$cartonTotal=$('#cartonTotal'),$netWeightTotal=$('#netWeightTotal'),$grossWeightTotal=$('#grossWeightTotal');
function generateDocNo() {
    show_loading();
    $.post(rurl('scm/serialNumber/generateDocNo'),{'type':'imp_order'},function (res) {
        if(isSuccess(res)){
            $('#docNo').val(res.data);
        }
    });
}
function fullCustomerData(cus){
    if(oldCustomerId!=cus.id){
        obtainImpQuote(cus.id);
        takeDeliveryInformation(cus.name);
    }
    oldCustomerId = cus.id;
}
//根据客户获取有效的协议报价
var impQuotes = {};
function obtainImpQuote(customerId,defBtVal,defIqVal,defTmVal) {
    if(isEmpty(customerId)){return;}
    show_loading();
    impQuotes = {};
    $.post(rurl('scm/agreement/impAgreement'),{'customerId':customerId},function (res) {
        if(isSuccess(res)){
            var data = res.data;
            if(data.length==0){
                prompt_warn('当前客户未找到有效协议报价!',function () {
                   $('#customerName').select();
                });
            }else{
                var $businessType = $('#businessType');
                $businessType.get(0).length = 0;
                if(data.length>1){
                    $businessType.append('<option value="">请选择</option>');
                }
                $.each(data,function (i,o) {
                    $businessType.append('<option value="'+o.businessType+'" '+(o.businessType==defBtVal?' selected ':'')+'>'+o.businessTypeName+'</option>');
                    impQuotes[o.businessType] = {"quotes":o.quotes,"transactionMode":o.transactionMode,"declareType":o.declareType,"declareTypeName":o.declareTypeName};
                });
                layui.form.render('select');
                fullImpQuote(defIqVal,defTmVal);
            }
        }
    });
}
//协议报价填充
function fullImpQuote(defIqVal,defTmVal) {
    var businessType = $('#businessType').val(),$impQuoteId = $('#impQuoteId');
    $impQuoteId.get(0).length = 0;
    if(!isEmpty(businessType)){
        var impAgreement = impQuotes[businessType];
        $.each(impAgreement.quotes || [],function (i,o) {
            $impQuoteId.append('<option value="'+o.id+'" '+(o.id==defIqVal?' selected ':'')+'>'+o.memo+'</option>');
        });
        //成交方式
        obtainTransactionMode(impAgreement.transactionMode,defTmVal);
        //报关类型
        $('#declareTypeName').val(impAgreement.declareTypeName);
    }
    layui.form.render('select');
}
function fullCurrencyData(data) {
    thisMonthRate(data.code);
}
//根据币制获取本月海关汇率
function thisMonthRate(currencyId) {
    var $showCustomsRate = $('#showCustomsRate');
    $showCustomsRate.hide();
    if(!isEmpty(currencyId)){
        $.post(rurl('system/customsRate/thisMonth'),{'currencyId':currencyId},function (res) {
            $showCustomsRate.html('海关汇率：'+(res.data || '')).show();
        });
    }
}

$('.addrow-btn').click(function () {createRow();});
$('#addSupplier').click(function () {
    var mid=parent.parent.obtainMIdByOperation('supplier_list'),taskArg={"documentId":"","documentClass":"","operation":"supplier_add"};
    if(isEmpty(mid)){prompt_warn('对不起您无此权限,请联系贵司管理员授权!');return;}
    setLocalStorage('TASK_'+mid,JSON.stringify({"customerName":$('#customerName').val()}));
    setLocalStorage('AUTO_TASK',JSON.stringify(taskArg));
    parent.parent.refreshTab(mid);
});
$('#maintainInformation').click(function () {
    var customerName = $('#customerName').val(),supplierName = $('#supplierName').val();
    if(!isEmpty(customerName)&&!isEmpty(supplierName)){
        var mid=parent.parent.obtainMIdByOperation('supplier_list'),taskArg={"documentId":supplierId,"documentClass":"","operation":"supplier_edit"};
        if(isEmpty(mid)){prompt_warn('对不起您无此权限,请联系贵司管理员授权!');return;}
        setLocalStorage('TASK_'+mid,JSON.stringify({"customerName":customerName,"name":supplierName}));
        setLocalStorage('AUTO_TASK',JSON.stringify(taskArg));
        parent.parent.refreshTab(mid);
    }else{
        show_error('请先选择境外供应商');
    }
});
$('#maintainDeliveryInformation').click(function () {
    var customerName = $('#customerName').val();
    if(!isEmpty(customerName)){
        var mid=parent.parent.obtainMIdByOperation('customer_list'),taskArg={"documentId":oldCustomerId,"documentClass":"","operation":"customer_edit"};
        if(isEmpty(mid)){prompt_warn('对不起您无此权限,请联系贵司管理员授权!');return;}
        setLocalStorage('TASK_'+mid,JSON.stringify({"name":customerName}));
        setLocalStorage('AUTO_TASK',JSON.stringify(taskArg));
        parent.parent.refreshTab(mid);
    }else{
        show_error('请先选择客户');
    }
});
function createRows(members) {
    var mhtml = [],tquantity = 0.0,ttotalPrice = 0.0,tcartonNum = 0,tnetWeight = 0.0,tgrossWeight = 0.0;
    $.each(members,function (i,o) {
        mhtml.push(createRowHtml(o.id,o.model,o.name,o.brand,o.unitName,o.quantity,o.unitPrice,o.totalPrice,o.cartonNum,o.netWeight,o.grossWeight,o.countryName,o.goodsCode,o.spec));
        tquantity+=o.quantity;ttotalPrice+=o.totalPrice;tcartonNum+=o.cartonNum;tnetWeight+=o.netWeight;tgrossWeight+=o.grossWeight;
    });
    $('#materialBody').append(mhtml.join(''));
    $quantityTotal.html(Math.round(tquantity*100)/100);
    $totalPriceTotal.html(formatCurrency(Math.round(ttotalPrice*100)/100));
    $cartonTotal.html(tcartonNum);
    $netWeightTotal.html(Math.round(tnetWeight*10000)/10000);
    $grossWeightTotal.html(Math.round(tgrossWeight*10000)/10000);
    autoAllModel();
    autoUnit();
    autoCountry();
    initInput();
    createIndex();
}
function createRow(mid,goodsModel,goodsName,goodsBrand,unitName,quantity,unitPrice,totalPrice,cartonNum,netWeight,grossWeight,countryName,goodsCode,goodsSpec) {
    if($('.mindex').length==50){show_error('最多添加50条产品信息！');return;}
    $('#materialBody').append(createRowHtml(mid,goodsModel,goodsName,goodsBrand,unitName,quantity,unitPrice,totalPrice,cartonNum,netWeight,grossWeight,countryName,goodsCode,goodsSpec));
    autoAllModel();
    autoUnit();
    autoCountry();
    initInput();
    createIndex();
    $('.tabBody').scrollTop(10000);
}
function createRowHtml(mid,goodsModel,goodsName,goodsBrand,unitName,quantity,unitPrice,totalPrice,cartonNum,netWeight,grossWeight,countryName,goodsCode,goodsSpec) {
    return [
        '<tr><td class="t-a-c mindex"></td>',
        '<td><input type="hidden" name="id" LIST value="'+(isEmpty(mid)?'':mid)+'"/><input type="text" name="model" LIST class="layui-input required auto-customer-model" placeholder="型号" value="'+(isEmpty(goodsModel)?'':goodsModel)+'"/></td>',
        '<td><input type="text" name="name" LIST class="layui-input" value="'+(isEmpty(goodsName)?'':goodsName)+'"/></td>',
        '<td><input type="text" name="brand" LIST class="layui-input required" value="'+(isEmpty(goodsBrand)?'':goodsBrand)+'"/></td>',
        '<td><input type="text" name="unitName" LIST class="layui-input auto-unit required" value="'+(isEmpty(unitName)?'个':unitName)+'"/></td>',
        '<td><input type="text" name="quantity" LIST onblur="calculationAll(this)" NUMBER class="layui-input required" value="'+(isEmpty(quantity)?'':quantity)+'"/></td>',
        '<td><input type="text" name="unitPrice" LIST class="layui-input layui-disabled" readonly value="'+(isEmpty(unitPrice)?'0.0000':unitPrice)+'"/></td>',
        '<td><input type="text" name="totalPrice" LIST onblur="calculationAll(this)" NUMBER class="layui-input required" value="'+(isEmpty(totalPrice)?'':totalPrice)+'"/></td>',
        '<td><input type="text" name="cartonNum" LIST onblur="calculationAll()" INT class="layui-input required" value="'+(isEmpty(cartonNum)?'0':cartonNum)+'"/></td>',
        '<td><input type="text" name="netWeight" LIST NUMBER4 onblur="calculationAll()" class="layui-input required" value="'+(isEmpty(netWeight)?'0.0000':netWeight)+'"/></td>',
        '<td><input type="text" name="grossWeight" LIST NUMBER4 onblur="calculationAll()" class="layui-input required" value="'+(isEmpty(grossWeight)?'0.0000':grossWeight)+'"/></td>',
        '<td><input type="text" name="countryName" LIST class="layui-input auto-country required" value="'+(isEmpty(countryName)?'中国':countryName)+'"/></td>',
        '<td><input type="text" name="goodsCode" LIST class="layui-input" value="'+(isEmpty(goodsCode)?'':goodsCode)+'"/></td>',
        '<td><input type="text" name="spec" LIST class="layui-input" value="'+(isEmpty(goodsSpec)?'':goodsSpec)+'"/></td>',
        '<td class="t-a-c"><a href="javascript:" onclick="deleteRow(this)"><i class="fa fa-trash-o"></i></a></td></tr>'
    ].join('');
}
function fullCustomerModelData(e,data) {
    var $per = $(e).parent().parent();
    $per.find('input[name="name"]').val(data.name);
    $per.find('input[name="brand"]').val(data.brand);
    $per.find('input[name="spec"]').val(data.spec);
}
function createIndex() {
    var mind = 1;
    $.each($('.mindex'),function (i,o) {
        $(o).html(mind++);
    });
}
function deleteRow(e) {
    var $per = $(e).parent().parent();
    $per.remove();
    createIndex();
    calculationAll();
}
function showOrHide(e) {
    $.each(e,function (i,o) {
        var $that = $(o);
        var $mark = $('[mark="'+$that.attr('id')+'"]');
        $mark.hide();
        $.each($mark,function (j,k) {
            var zmkeys = $(k).attr('zm-key').split(",");
            if(contain(zmkeys,$that.val())){
                $(k).show();
            }
        });
    });
}
function calculationAll(e) {
    var tquantity = 0.0,ttotalPrice = 0.0,tcartonNum = 0,tnetWeight = 0.0,tgrossWeight = 0.0;
    if(!isEmpty(e)){
        var $that = $(e),$parent=$that.parent().parent(),$quantity=$parent.find('input[name="quantity"]'),$unitPrice=$parent.find('input[name="unitPrice"]'),$totalPrice=$parent.find('input[name="totalPrice"]');
        switch ($that.attr('name')){
            case 'quantity':
                var quantity = Math.round(parseFloat($quantity.val() || '0.0')*100)/100;
                var totalPrice = Math.round(parseFloat($totalPrice.val() || '0.0')*100)/100;
                $unitPrice.val(Math.round(totalPrice/quantity*10000)/10000);
                break;
            case 'unitPrice':
                var quantity = Math.round(parseFloat($quantity.val() || '0.0')*100)/100;
                var unitPrice = Math.round(parseFloat($unitPrice.val() || '0.0')*10000)/10000;
                $totalPrice.val(Math.round(quantity*unitPrice*100)/100);
                break;
            case 'totalPrice':
                var quantity = Math.round(parseFloat($quantity.val() || '0.0')*100)/100;
                if(quantity==0.0){$unitPrice.val('0.0000');return;}
                var totalPrice = Math.round(parseFloat($totalPrice.val() || '0.0')*100)/100;
                $unitPrice.val(Math.round(totalPrice/quantity*10000)/10000);
                break;
        }
    }
    $.each($('#materialBody').find('tr'),function (i,o) {
        var $that = $(o);
        tquantity += Math.round(parseFloat($that.find('input[name="quantity"]').val() || '0.0')*100)/100;
        ttotalPrice += Math.round(parseFloat($that.find('input[name="totalPrice"]').val() || '0.0')*100)/100;
        tcartonNum += parseInt($that.find('input[name="cartonNum"]').val() || '0');
        tnetWeight += Math.round(parseFloat($that.find('input[name="netWeight"]').val() || '0.0')*10000)/10000;
        tgrossWeight += Math.round(parseFloat($that.find('input[name="grossWeight"]').val() || '0.0')*10000)/10000;
    });
    $quantityTotal.html(Math.round(tquantity*100)/100);
    $totalPriceTotal.html(formatCurrency(Math.round(ttotalPrice*100)/100));
    $cartonTotal.html(tcartonNum);
    $netWeightTotal.html(Math.round(tnetWeight*10000)/10000);
    $grossWeightTotal.html(Math.round(tgrossWeight*10000)/10000);
}
//选择供应商
function fullSupplierData(data) {
    supplierId = data.id;
    takeInformation(data.name);
}
//获取提货地址
function takeInformation(name,defVal){
    var customerName = $('#customerName').val(),supplierName = (name || $('#supplierName').val());
    if(!isEmpty(customerName)&&!isEmpty(supplierName)){
        var takeInformationsObj = $('#takeInformations');
        takeInformationsObj.html('<img src="'+rurl('images/indicator.gif')+'"/>');
        $.post(rurl('scm/supplierTakeInfo/effectiveList'),{'customerName':customerName,'supplierName':supplierName},function (res) {
            var thtml = [];
            $.each((res.data || []),function (i,o) {
                if(isEmpty(defVal)){defVal = o.id;}
                thtml.push('<div class="range-list-item"><input type="radio" name="supplierTakeInfoId" value="'+o.id+'" title="【'+o.companyName+'】'+o.provinceName+o.cityName+o.areaName+o.address+' ('+o.linkPerson+' '+o.linkTel+')" '+(o.id==defVal?'checked="true"':'')+'></div>');
            });
            takeInformationsObj.html(thtml.join(""));
            layui.form.render('radio');
        });
    }else{
        show_error('请先选择境外供应商');
    }
}
//获取客户收货地址
function takeDeliveryInformation(name,defDiVal){
    var customerName = (name || $('#customerName').val());
    if(!isEmpty(customerName)){
        var deliveryInformationsObj = $('#deliveryInformations');
        deliveryInformationsObj.html('<img src="'+rurl('images/indicator.gif')+'"/>');
        $.post(rurl('scm/customerDeliveryInfo/effectiveList'),{'customerName':customerName},function (res) {
            var thtml = [];
            $.each((res.data || []),function (i,o) {
                if(isEmpty(defDiVal)){defDiVal=o.id;}
                thtml.push('<div class="range-list-item"><input type="radio" name="customerDeliveryInfoId" value="'+o.id+'" title="【'+o.companyName+'】'+o.provinceName+o.cityName+o.areaName+o.address+' ('+o.linkPerson+' '+o.linkTel+')" '+(o.id==defDiVal?'checked="true"':'')+'></div>');
            });
            deliveryInformationsObj.html(thtml.join(""));
            layui.form.render('radio');
        });
    }else{
        show_error('请先选择客户');
    }
}
//获取自提仓库
function takeSelfWare(defVal) {
    $.get(rurl('scm/warehouse/selfWarehouses'),{},function (res) {
        if(isSuccess(res)){
            var $selfWare = $('#selfWare');
            $.each(res.data||[],function (i,o) {
                $selfWare.append('<option value="'+o.id+'" '+(o.id==defVal?' selected ':'')+'>'+o.detailDesc+'</option>');
            });
            layui.form.render('select');
        }
    });
}
//获取国内物流信息
function domesticLogistics(defDlVal,defLtVal) {
    var logisticsstr = getLocalStorage('static_domestic_logistics');
    if(isEmpty(logisticsstr)){
        $.get(rurl('scm/domesticLogistics/select'),{},function (res) {
            if(isSuccess(res)){
                var logisticsData = res.data;
                setLocalStorage('static_domestic_logistics',JSON.stringify(logisticsData));
                initDomesticLogistics(defDlVal,defLtVal);
            }
        });
    }else{
        initDomesticLogistics(defDlVal,defLtVal);
    }
}
function initDomesticLogistics(defDlVal,defLtVal){
    var logisticsData = JSON.parse(getLocalStorage('static_domestic_logistics') || "[]"),
        $logisticsCompany = $('#logisticsCompany');
    $.each(logisticsData || [],function (i,o) {
        $logisticsCompany.append('<option value="'+o.id+'" '+(o.id == defDlVal?' selected ':'')+'>'+o.name+'</option>');
    });
    layui.form.render('select');
    logisticsTimeliness(defLtVal);
}
//物流公司时效展示
function logisticsTimeliness(defLtVal) {
    var $askContainer = $('#askContainer'),logisticsCompany = $('#logisticsCompany').val(),
        logisticsData = JSON.parse(getLocalStorage('static_domestic_logistics') || "[]"),bhtml = [];
    $.each(logisticsData || [],function (i,o) {
        if(o.id==logisticsCompany){
            if(o.timeline != null && o.timeline.length > 0) {
                $.each(o.timeline,function (i,o) {
                    if(isEmpty(defLtVal)){defLtVal=o;}
                    bhtml.push('<input type="radio" name="prescription" value="'+o+'" title="'+o+'" '+(o==defLtVal?'checked':'')+'/>');
                });
            }
        }
    });
    $askContainer.html(bhtml.join(''));
    layui.form.render('radio');
}
//获取所有成交方式
function obtainTransactionMode(optionalVal,defaultVal){
    var transactionModestr = getLocalStorage('static_transaction_mode');
    if(isEmpty(transactionModestr)){
        $.get(rurl('scm/common/bizSelect'),{'type':'TransactionMode'},function (res) {
            if(isSuccess(res)){
                var transactionModeData = res.data['TransactionMode'];
                setLocalStorage('static_transaction_mode',JSON.stringify(transactionModeData));
                initTransactionMode(optionalVal,defaultVal);
            }
        });
    }else{
        initTransactionMode(optionalVal,defaultVal);
    }
}
function initTransactionMode(optionalVal,defaultVal) {
    var transactionModeData = JSON.parse(getLocalStorage('static_transaction_mode') || "[]"),$transactionMode=$('#transactionMode');
    $transactionMode.get(0).length = 0;
    if(isEmpty(optionalVal)){
        $transactionMode.append('<option value="">请选择</option>');
    }
    $.each(transactionModeData || [],function (i,o) {
        if(isEmpty(optionalVal) || (!isEmpty(optionalVal)&&optionalVal==o.value)){
            $transactionMode.append('<option value="'+o.value+'" '+((!isEmpty(defaultVal)&&defaultVal==o.value)?' selected ':'')+'>'+o.label+'</option>');
        }
    });
    layui.form.render('select');
}

app.obtainSubject(function (sub) {
   $('#subjectName').val(sub['name']);
   $('#subjectId').val(sub['id']);
});
//订单明细
function obtainMenberJSON() {
    var members = [],orderMember = $('#orderMemberForm').serializeJson(),keys=[];
    for(var key in orderMember){keys.push(key);}
    $.each(orderMember[keys[0]] ||[],function (i,o) {
        var item = {};
        $.each(keys,function (j,k) {
            item[k] = orderMember[k][i];
        });
        members.push(item);
    });
    return members;
}